from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver
import pyautogui as pi
import xlrd
import time
url_address = '/member/login/executeLogin.htm'
url_uat = 'http://61.187.51.25:8084'
url_dev = 'http://61.187.51.25:8800'
url_prod = 'https://www.holdcg.com'
url_local = 'http://localhost:6850'
PHONE = "13271592077"
filepath = ".\create_project_settings.xls"
workbook =  xlrd.open_workbook(filepath)
worksheet1 = workbook.sheet_by_name('sheet1')
class Setting:
    def __init__(self):
        self.p_type = ""
        self.worksheet = worksheet1
        self.log_file = open("createlog.txt","a")
    def debug_print(self,s):
        self.write_log(s)
    def write_log(self,s):
        time_now = time.localtime()
        date_now = time.strftime('%Y-%m-%d',time_now)
        format_log_str = "%s ---> %s \n" %  (date_now,s)
        print(format_log_str)
        self.log_file.write(format_log_str)
    def getIsDebug(self):
        return str(self.worksheet.cell_value(1,8))
    def getAccount(self):
        return str(self.worksheet.cell_value(1,0))
    def getName(self):
        return str(self.worksheet.cell_value(1,1))
    def getID(self):
        return str(int(self.worksheet.cell_value(1,3)))
    def getBudget(self):
        return str(int(self.worksheet.cell_value(1,4)))
    def getCustomurl(self):
        url_custom = str(self.worksheet.cell_value(2,2))
        return "http://"+url_custom
    def setTypeProject(self,p_type):
        self.p_type = p_type
    def getTypeProject(self):
        return self.p_type
    def getUrl(self):
        url_excel=str(self.worksheet.cell_value(1,2))
        url_address = '/member/login/executeLogin.htm'
        if url_excel.upper()=='DEV':
            return url_dev + url_address
        elif url_excel.upper()=='UAT':
            return url_uat + url_address
        elif url_excel.upper()=='LOCAL':
            return url_local + url_address
        elif url_excel.upper()=='PROD':
            return url_prod + url_address
        elif url_excel.upper()=='CUSTOM':
            return customurl1 + url_address


settings = Setting()
account1 = settings.getAccount()
budget1 = settings.getBudget()
customurl1 = settings.getCustomurl()
id1 = settings.getID()
name1 = settings.getName()
url1 = settings.getUrl()
debugStr = settings.getIsDebug()


    
PASSWORD = 's#f]A4@_a;M,d-c[lPn)'
    
def isDaili(account):
    begin_str = account[0:2]
    if begin_str == 'xz':
        return True
    else:
        return False

def pmlogin(driver, url):
    driver.get(url)
    settings.debug_print("Login address : %s" % url)
    settings.debug_print("Login user account : %s " % account1)
    locationLogin = (By.LINK_TEXT, '立即登录')
    try:
        WebDriverWait(driver, 20, 0.5).until(presence_of_element_located(locationLogin))
    except Exception as e:
        settings.debug_print(e)
        settings.debug_print("登录失败")
    driver.find_element(By.ID, 'username').send_keys(account1)
    driver.find_element(By.ID, 'xstr').send_keys(PASSWORD)
    driver.find_element(By.LINK_TEXT, '立即登录').click()

def go2myproject(driver):
    driver.find_element(By.LINK_TEXT, '采购').click()
    driver.find_element(By.LINK_TEXT, '我的项目').click()
    x1="//span[@title='进行中的项目']"
    driver.find_element(By.XPATH,x1).click()
    # 添加项目
    x1="//button[@data-toggle='dropdown']"
    driver.find_element(By.XPATH,x1).click()

def getTimeStrip():
    #return time.strftime("%Y{}%m{}%d{} %H{}%M{}%S{}",time.localtime()).format('年','月','日','时','分','秒')
    return time.strftime("%Y{}%m{}%d{}-%H{}%M{}",time.localtime()).format('年','月','日','时','分')

def daliInfo(driver):
    x1 = """//span[@id="selectConsignContract"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    x1 = """//input[@placeholder="委托合同名称"]"""
    try:
        driver.find_element(By.XPATH,x1).send_keys("test")
    except Exception as e:
        settings.debug_(e+"not found name of the test contract")
    time.sleep(2)
    x1 = """//button[@id="modalDialogSearchBtn"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(3)
    x1 = """//input[@id="modalDialogId0"]"""
    driver.find_element(By.XPATH,x1).click()
    x1 = """//button[@id="modalDialogSelect"]"""
    driver.find_element(By.XPATH,x1).click()
    # 代理服务收取对象
    x1 = """//button[@data-id="serviceReceiveObject"]"""
    driver.find_element(By.XPATH,x1).click()
    try:
        driver.find_element(By.LINK_TEXT,"中标人").click()
    except Exception as e:
        settings.debug_print(e)
        driver.find_element(By.LINK_TEXT,"成交人").click()
    x1 = """//button[@data-id="serviceFeeMode"]"""
    try:
        driver.find_element(By.XPATH,x1).click()
        driver.find_element(By.LINK_TEXT,"固定金额").click()
    except Exception as e:
        settings.debug_print(e+"固定金额 can not click")
        x1 = """//button[@data-id="serviceReceiveObject"]"""
        driver.find_element(By.XPATH,x1).click()
        driver.find_element(By.LINK_TEXT,"招标人").click()
    x1 = """//input[@name="exampelid3"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    x1 = """//td[@class="today active start-date active end-date available"]"""
    driver.find_element(By.XPATH,x1).click()
    try:
        x1 = """//input[@name="totalInvestment"]"""
        driver.find_element(By.XPATH,x1).send_keys(budget1)
    except Exception as e:
        settings.debug_print(e+"budget element not found")
    #招标人
    x1 = """//span[@id="selectTenderee"]"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    x1 = """//input[@placeholder="招标人名称"]"""
    try:
        driver.find_element(By.XPATH,x1).send_keys("湖南大学")
    except Exception as e:
        settings.debug_print(e)
        try:
            x1 = """//input[@placeholder="采购单位名称"]"""
            driver.find_element(By.XPATH,x1).send_keys("湖南大学")
        except Exception as e:
            settings.debug_print(e)
            x1 = """//input[@placeholder="采购人名称"]"""
            driver.find_element(By.XPATH,x1).send_keys("湖南大学")
    x1 = """//button[@class="btn btn-primary btn-flat searchBtn"]/span"""
    driver.find_element(By.XPATH,x1).click()
    time.sleep(2)
    x1 = """//input[@id="modalDialogId0"]"""
    driver.find_element(By.XPATH,x1).click()
    x1  = """//button[@id="modalDialogSelect"]"""
    driver.find_element(By.XPATH,x1).click()
    try:
        x1 = """//button[@id="popup_cancel"]"""
        driver.find_element(By.XPATH,x1).click()
    except:
        settings.debug_print("not found cancel button")
def baseInfo(driver):
    # 项目名称
    x1 = """//input[@class="form-control unNameBlanks required"]"""
    driver.find_element(By.XPATH,x1).send_keys("Test-"+settings.getTypeProject()+"-"+getTimeStrip())
    try:
        # 行业类别
        x1 = """//button[@data-id="industryCategory"]"""
        driver.find_element(By.XPATH,x1).click()
        driver.find_element(By.LINK_TEXT,"不限").click()
        # 项目分类
        x1 = """//button[@data-id="bidTypeSelect"]"""
        driver.find_element(By.XPATH,x1).click()
        driver.find_element(By.LINK_TEXT,"货物").click()
        x1 = """//button[@data-id="bidTypeSecondSelect"]"""
        driver.find_element(By.XPATH,x1).click()
        driver.find_element(By.LINK_TEXT,"材料").click()
        # 项目所属地区
        x1="""//button[@data-id="projectareaProvince"]"""
        driver.find_element(By.XPATH,x1).click()
        #湖南
        x1 = """//div/div[@class="bs-container btn-group bootstrap-select required noCheck dropup open"]//ul/li[@data-original-index="18"]/a"""
        driver.find_element(By.XPATH,x1).click()
        # 需求部门
        x1 = """//input[@name="v(requireDepartName@String)"]"""
        driver.find_element(By.XPATH,x1).send_keys('需求部门')
        x1 = """//input[@name="v(requireLinkName@String)"]"""
        driver.find_element(By.XPATH,x1).send_keys(name1)
        x1 = """//input[@placeholder="请输入需求部门联系方式"]"""
        driver.find_element(By.XPATH,x1).send_keys(PHONE)
        x1 = """//input[@id="budgetAmount"]"""
        driver.find_element(By.XPATH,x1).send_keys(budget1)
    except Exception as e:
        #print(e)
        settings.debug_print("baseInfo Element not found")

def yijx(driver):
        x1 = """//span[@id="selectLinkName"]"""
        driver.find_element(By.XPATH,x1).click()
        time.sleep(2)
        x1 = """//div[@class="filtrate-box"]/input"""
        driver.find_element(By.XPATH,x1).send_keys(name1)
        x1 = """//button[@id="modalDialogSearchBtn"]"""
        driver.find_element(By.XPATH,x1).click()
        x1 = """//input[@id="modalDialogId0"]"""
        driver.find_element(By.XPATH,x1).click()
        x1 = """//button[@id="modalDialogSelect"]"""
        driver.find_element(By.XPATH,x1).click()
        x1 = """//input[@id="budgetAmount"]"""
        driver.find_element(By.XPATH,x1).send_keys(budget1)

def inputInfo(driver):
    if isDaili(account1):
        baseInfo(driver)
        daliInfo(driver)
    else:
        baseInfo(driver)

# test
def createProjectMain(driver):
    if(id1[0]=='1'):    
        # CA项目
        x1 = """//a[@href="#home1"]"""
        driver.find_element(By.XPATH,x1).click()
        #driver.find_element(By.LINK_TEXT,"网上开评标（需CA）").click()
        if(id1[1]=='1'):
            # 招标项目
            settings.setTypeProject("CA企业招标：")
            settings.debug_print("CA企业招标")
            x1="""//*[@id="home1"]/button[@class='btn btn-default zb']"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
        elif(id1[1]=='2'):
            # 竞争性谈判
            settings.setTypeProject("CA竞争性谈判:")
            settings.debug_print("CA竞争性谈判")
            x1 = """//*[@id="home1"]/button[@class="btn btn-default jzxtp"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
            #供应商报名
            x1 = """//input[@id="bidForms2010"]"""
            driver.find_element(By.XPATH,x1).click()
        elif(id1[1]=='3'):
            # 询价采购
            settings.setTypeProject("CA询价采购项目:")
            settings.debug_print("CA询价采购项目")
            x1 = """//*[@id="home1"]/button[@class="btn btn-default xjcg"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
            #供应商报名
            x1 = """//input[@id="bidForms4010"]"""
            driver.find_element(By.XPATH,x1).click()
        elif(id1[1]=='4'):
            #竞争性磋商
            settings.setTypeProject("CA竞争性谈判项目:")
            settings.debug_print("CA竞争性谈判项目")
            x1 = """//*[@id="home1"]/button[@class="btn btn-default jzxcs"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
            #供应商报名
            x1 = """//input[@id="bidForms9010"]"""
            driver.find_element(By.XPATH,x1).click()
        elif(id1[1]=='5'):
            #供应商入围
            settings.setTypeProject("CA供应商入围:")
            settings.debug_print("CA供应商入围")
            x1 = """//*[@id="home1"]/button[@class="btn btn-default gysrw"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)

    elif(id1[0]=='2'):
        # 网上开评标 无需CA
        x1 = """//a[@href="#profile1"]"""
        driver.find_element(By.XPATH,x1).click()
        #driver.find_element(By.LINK_TEXT,"网上开评标（无需CA)").click()
        if(id1[1]=='1'):
            #单一来源采购项目
            settings.setTypeProject("无CA单一来源:")
            settings.debug_print("无CA单一来源")
            x1 = """//*[@id="profile1"]/button[@class="btn btn-default dylycg"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
            #税率填写人-供应商
            x1 = """//input[@id="taxWay20"]"""
            driver.find_element(By.XPATH,x1).click()
        elif(id1[1]=='2'):
            #竞价项目
            settings.setTypeProject("无CA竞价项目:")
            settings.debug_print("无CA竞价项目")
            x1 = """//*[@id="profile1"]/button[@class="btn btn-default jj"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
            #价格梯度
            x1 = """//input[@id="gradientPrice"]"""
            driver.find_element(By.XPATH,x1).send_keys("300")
        elif(id1[1]=='3'):
            #谈判采购
            settings.setTypeProject("无CA谈判采购项目:")
            settings.debug_print("无CA谈判采购项目")
            x1 = """//*[@id="profile1"]/button[@class="btn btn-default jzxtpxm3"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
            #税率填写人-供应商
            x1 = """//input[@id="taxWay20"]"""
            driver.find_element(By.XPATH,x1).click()
        elif(id1[1]=='4'):
            #询价采购项目
            settings.setTypeProject("无CA询价采购项目:")
            settings.debug_print("无CA询价采购项目")
            x1 = """//*[@id="profile1"]/button[@class="btn btn-default xbjxm3"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
            #税率填写人-供应商
            x1 = """//input[@id="taxWay20"]"""
            driver.find_element(By.XPATH,x1).click()
        elif(id1[1]=='5'):
            #供应商入围
            settings.setTypeProject("无CA供应商入围:")
            settings.debug_print("无CA供应商入围")
            x1 = """//*[@id="profile1"]/button[@class="btn btn-default gysrw"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
        elif(id1[1]=='6'):
            #议价项目
            settings.setTypeProject("无CA议价项目:")
            settings.debug_print("无CA议价项目")
            x1 = """//*[@id="profile1"]/button[@class="btn btn-default yj"]"""
            driver.find_element(By.XPATH,x1).click()
            inputInfo(driver)
            yijx(driver)
            #税率填写人-供应商
            x1 = """//input[@id="taxWay20"]"""
            driver.find_element(By.XPATH,x1).click()
        else:
            pi.alert("wrong project ID in excel")
    
if __name__ == '__main__':
    options = webdriver.ChromeOptions()
    settings.debug_print("Chrome webdriver starting")
    options.add_argument('--args --disable-web-security')
    options.add_argument('--start-maximized')
    options.add_argument('--incognito')
    options.add_argument('--lang=zh-CN')
    options.add_argument('disable-infobars')
    options.add_experimental_option('useAutomationExtension', False)
    options.add_experimental_option("excludeSwitches", ['enable-automation'])
    driver = webdriver.Chrome(options=options)
    driver.implicitly_wait(30)
    pmlogin(driver,url1)
    go2myproject(driver)
    createProjectMain(driver)
    if debugStr.upper()=="Y":
        pi.alert("DONE")
    settings.debug_print("===========done===========")
